﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using StampController.BL;
using StampController.BL.Models;
using StampController.Core;
using StampController.Helpers;
using log4net;

namespace StampController.Pages
{
    public partial class RequestForm : BasePage
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(RequestForm).Name);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var user = SessionUtils.Get<UsersModel>("USER");

                string requestId = Request.QueryString["q"];
                if (!string.IsNullOrEmpty(requestId))
                {
                    // Approved -> Redirect
                    var im = new RequestFormImpl();
                    var model = im.GetRequestForm(requestId);

                    if (model.LastApprovedDate.HasValue)
                        Response.Redirect("/");
                }
                //else
                //{
                //    txtDepartment.Text = user.DeptName;
                //    txtDateOfApp.Text = DateTime.Now.ToShortDateString();
                //}

                var categories = new CategoryImpl().GetCategoryList();
                categories.Insert(0, new CategoryModel { CategoryId = 0, CategoryName = "-- Select a category --" });
                ddlCategory.DataSource = categories;
                ddlCategory.DataValueField = "CategoryId";
                ddlCategory.DataTextField = "CategoryName";
                ddlCategory.DataBind();

                var users = new UsersImpl().GetUserList().Where(x => x.UserID != user.UserID).ToList();
                users.Insert(0, new UsersModel { UserID = null, Name = "-- Request for --" });
                ddlRequestFor.DataSource = users;
                ddlRequestFor.DataValueField = "UserID";
                ddlRequestFor.DataTextField = "Name";
                ddlRequestFor.DataBind();

                //add item for request type
                var items = new List<ListItem> { new ListItem("Normal", "1"), new ListItem("Urgent", "2") };
                ddlRequestType.Items.AddRange(items.ToArray());
            }
        }

        [WebMethod]
        public static bool SaveRequest(RequestFormModel request)
        {
            var currentUser = SessionUtils.Get<UsersModel>("USER");
            if (currentUser == null)
            {
                return false;
            }

            //Log the submit stamp request user
            logger.Debug(currentUser.UserID+" is submitting a new stamp request...");

            var im = new RequestFormImpl();
            request.DateRequest = DateTime.Now;
            request.UserID = currentUser.UserID;
            request.STID = 0;
            foreach (var i in request.STList)
            {
                request.STID = request.STID.Add(i);
            }
            if (!string.IsNullOrEmpty(request.RequestFor))
            {
                var userImpl = new UsersImpl();
                currentUser = userImpl.GetUser(request.RequestFor);
            }
            bool sendMail = false;
            if (request.AssignedTo != currentUser.DeptID)
            {
                // Ignore Update MODE
                request.AssignedTo = currentUser.DeptID;
                // Send mail to HOD
                sendMail = true;
            }
            if (request.CategoryId == 0) request.CategoryId = null;
            var result = im.SaveRequestForm(request);
            if (result && sendMail)
            {
                MailHelper.Send(ApprovalStatus.NewRequest, UserType.NormalUser, currentUser, im.GetRequestForm(request.ID), "/pages/ApprovalRequestForm.aspx");
            }

            //Log the submit user
            logger.Debug(request.UserID + " has just submitted a new stamp request successfully with ID=" + request.ID);

            return result;
        }

        [WebMethod]
        public static RequestFormModel GetItem(string requestId)
        {
            var im = new RequestFormImpl();
            var model = im.GetRequestForm(requestId);
            model.STList = new List<int>();
            for (int i = 0; Math.Pow(2, i) <= model.STID; i++)
            {
                if (model.STID.Has((int)Math.Pow(2, i)))
                    model.STList.Add((int)Math.Pow(2, i));     
            }
            return model;
        }

        [WebMethod]
        public static bool DeleteDocument(string requestId, string filepath)
        {
            var im = new DocumentImpl();
            var result = im.DeleteDocument(requestId, filepath);
            if (result)
            {
                string uploadFolder =
                    HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadFolder"]);
                if (File.Exists(uploadFolder + filepath))
                {
                    File.Delete(uploadFolder + filepath);
                }
            }
            else
            {
                throw new NullReferenceException();
            }

            return true;
        }

        [WebMethod]
        public static bool DeleteFile(string filepath)
        {
            string uploadFolder =
                HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadFolder"]);
            if (File.Exists(uploadFolder + filepath))
            {
                File.Delete(uploadFolder + filepath);
            }

            return true;
        }

        [WebMethod]
        public static bool DeleteFiles(string[] filepaths)
        {
            string uploadFolder =
                HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadFolder"]);
            foreach (var filepath in filepaths)
            {
                if (File.Exists(uploadFolder + filepath))
                {
                    File.Delete(uploadFolder + filepath);
                }
            }

            return true;
        }
    }
}